<template>
  <div>
    <el-drawer
      title="余额查询"
      :visible="showBalanceDrawer"
      direction="rtl"
      size="50%"
      :before-close="handleClose"
      custom-class="demo-drawer"
    >
      <!-- <div v-if="cardUseRangeFlag == 1" style="margin-bottom: 20px;font-size: 24px;">电子卡总余额{{totalBalance}}元</div> -->
      <!-- 所有点击卡余额列表 -->
      <el-table
        :data="balanceList"
        v-show="!isDetails"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="left">
        </el-table-column>
        <el-table-column
          property="cardOilsType"
          label="电子卡类型"
          :formatter="formatterDzkType"
        ></el-table-column>
        <!-- <el-table-column
          :property="cardUseRangeFlag === '1' ? 'amt' : 'totalAmt'"
          label="总余额(元)"
        ></el-table-column> -->
        <el-table-column
          property="totalAmt"
          label="总余额(元)"
        ></el-table-column>
        <el-table-column
          property="recentlyTime"
          label="最后一次变更时间"
          show-overflow-tooltip
        ></el-table-column>
        <af-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="balanceDetails(scope.row)"
              v-if="cardUseRangeFlag === '2'"
            >
              查看
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleAdjust(scope.row)"
              v-if="cardUseRangeFlag === '1'"
            >
              调整余额
            </el-button>
          </template>
        </af-table-column>
      </el-table>

      <!-- 一个点击卡余额明细列表 -->
      <el-table :data="balanceDetailsList" v-show="isDetails">
        <el-table-column type="index" label="序号" width="80" align="left">
        </el-table-column>
        <el-table-column
          property="cardOilsType"
          label="电子卡类型"
          width="150"
          :formatter="formatterDzkType"
        ></el-table-column>
        <!-- <el-table-column
          property="amt"
          show-overflow-tooltip
          label="金额(元)"
          width="200"
        ></el-table-column> -->
        <el-table-column
          property="totalAmt"
          show-overflow-tooltip
          label="金额(元)"
          width="200"
        ></el-table-column>
        <el-table-column
          property="stationName"
          show-overflow-tooltip
          label="所属油站"
        ></el-table-column>
        <el-table-column
          property="recentlyTime"
          label="最后一次变更时间"
          width="250"
        ></el-table-column>
        <af-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleAdjust(scope.row)">
              调整余额
            </el-button>
          </template>
        </af-table-column>
      </el-table>
      <el-button
        style="float: right; margin: 15px 10px 0 0"
        v-show="isDetails"
        type="primary"
        @click="isDetails = false"
        >返回</el-button
      >
    </el-drawer>

    <!-- 余额调增弹框 -->
    <el-dialog
      title="调整余额"
      :visible.sync="showAdjust"
      width="40%"
      class="updateDrawer"
    >
      <el-form
        :model="customerCardChangeDto"
        label-position="top"
        :rules="customerCardChangeDtoRules"
        ref="adjustRef"
      >
        <el-form-item
          v-if="cardUseRangeFlag === '1'"
          label="选择油站"
          prop="stationId"
          clearable
          size="small"
        >
          <el-select
            v-model="customerCardChangeDto.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
            style="width: 100%"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调整金额" prop="amt">
          <div
            style="
              display: flex;
              flex-direction: column;
              align-items: flex-start;
            "
          >
            <div class="div1">
              <span>当前余额(元)</span><br />
              <b>{{ currentCardBlanceTotal }}</b>
            </div>
            <div
              class="div2"
              style="width: 100%; display: flex; align-items: center"
            >
              <el-select
                v-model="customerCardChangeDto.operateType"
                placeholder="请选择"
                style="width: 130px"
                size="small"
              >
                <el-option label="增加" value="0"> </el-option>
                <el-option label="扣减" value="1"> </el-option>
              </el-select>
              <el-input
                maxlength="11"
                show-word-limit
                v-model="customerCardChangeDto.amt"
                placeholder="请输入"
                style="flex: 1"
                size="small"
              />
              (元)
            </div>
            <div class="div3">
              <span>调整后余额(元)</span><br />
              <b>{{ affterAmt }}</b>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="赠送优惠券(非必选)" prop="couponId">
          <el-select
            v-model="customerCardChangeDto.couponIds"
            placeholder="请选择"
            size="small"
            style="width: 100%"
            clearable
            filterable
            multiple
            collapse-tags
          >
            <el-option
              v-for="(item, index) in couponList"
              :key="item.id"
              :value="item.id"
              :label="item.couponRemark"
            >
              <span style="float: left">{{ item.couponRemark }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                ID:{{ item.id }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推送消息" prop="messagePush">
          <el-radio-group v-model="customerCardChangeDto.messagePush">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="reason">
          <el-input
            type="text"
            maxlength="20"
            show-word-limit
            placeholder="请输入内容"
            size="small"
            v-model="customerCardChangeDto.reason"
            clearable
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="操作人" prop="operator">
          <el-select
            v-model="customerCardChangeDto.operator"
            clearable
            placeholder="请选择"
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="(item, index) in staffList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdjust = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleAdjustSubmit"
          :loading="adjustSubmitLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listEnterpriseStation } from "@/api/dept";
import {
  cardUserList,
  updateUserRecord,
  electronicCardUpdateUserRecordApi,
} from "@/api/customer/manage";
import { creationList } from "@/api/coupon/creation";
import { getStaffQuery } from "@/api/station/personnel";
import { cloneDeep } from "lodash";
export default {
  name: "CustomerBlance",
  props: {
    showBalanceDrawer: {
      type: Boolean,
      default: false,
    },

    currenRowData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    let checkAmt = (rule, value, callback) => {
      let money = Number(String(value).trim());
      const pattern = /^\d+(\.\d{1,2})?$/;
      if (!value) return callback(new Error("请输入金额"));
      if (value.startsWith(".")) return callback(new Error("请输入有效数值"));
      if (Number.isNaN(money)) return callback(new Error("请输入有效数值"));
      if (money <= 0) return callback(new Error("金额不能小于等于0"));
      if (!pattern.test(money))
        return callback(new Error("金额最多只能保留两位小数点"));
      if (parseFloat(this.affterAmt) < 0)
        return callback(new Error("调整金额不能大于总余额"));

      callback();
    };
    return {
      balanceList: [],
      isDetails: false,
      balanceDetailsList: [],
      customerCardChangeDto: {
        messagePush: "0",
        amt: null,
        couponId: null,
        operateType: "0",
        stationId: null,
      },
      customerCardChangeDtoRules: {
        stationId: [
          { required: true, message: "请选择油站", trigger: "change" },
        ],
        amt: [
          {
            required: true,
            validator: checkAmt,
            trigger: "change",
          },
        ],
        messagePush: [
          { required: true, message: "请选择是否推送消息", trigger: "change" },
        ],
        reason: [{ required: true, message: "请输入备注", trigger: "blur" }],
        // operator: [
        //   { required: true, message: "选择操作人", trigger: "change" },
        // ],
      },
      stationList: [],
      showAdjust: false, // 调整余额弹框
      cardUseRangeFlag: "", // 1-多站通用，2-单站使用
      couponList: [], // 优惠券列表
      currentCardBlanceTotal: 0, // 当前选中电子卡的总余额
      loading: false,
      staffList: [], // 员工列表
      adjustSubmitLoading: false, // 确定按钮的loading
    };
  },
  computed: {
    affterAmt() {
      let inputAmt;
      let amtTem = parseFloat(this.currentCardBlanceTotal);
      if (this.customerCardChangeDto.amt) {
        inputAmt = parseFloat(this.customerCardChangeDto.amt);
      } else {
        inputAmt = 0;
      }
      if (this.customerCardChangeDto.operateType === "0") {
        console.log("增加");
        amtTem = amtTem + inputAmt;
      } else {
        amtTem = amtTem - inputAmt;
      }
      return amtTem.toFixed(2);
    },
  },
  watch: {
    showBalanceDrawer(val) {
      if (val) {
        this.getCardUserList();
      }
    },
    showAdjust(val) {
      if (val) {
        this.getStationList(this.currenRowData.stationId);
        this.getCouPonList();
        this.toGetStaffQuery();
      }
    },
  },

  methods: {
    handleClose() {
      this.$emit("update:showBalanceDrawer", false);
      this.isDetails = false;
    },

    // // 获取油站列表
    // getStationList(val) {
    //   listEnterpriseStation({ enterpriseId: val }).then((res) => {
    //     console.log(res, "333");
    //     if (res.length === 1) {
    //       this.customerCardChangeDto.stationId = res[0].stationId;
    //     } else {
    //       this.stationList = res;
    //     }
    //   });
    // },

    // 获取员工列表
    async toGetStaffQuery() {
      const params = {};
      // 油企账号
      if (this.$store.state.user.userLevel === "1") {
        params.enterpriseId = this.presentEnterprise.enterpriseId;
      } else if (this.$store.state.user.userLevel === "2") {
        // 油站账号
        params.enterpriseId = this.presentEnterprise.enterpriseId;
        params.stationId = this.$store.state.user.stationId;
      }
      const res = await getStaffQuery(params);
      this.staffList = res.rows;
    },

    // 获取用户各种卡的余额
    getCardUserList() {
      this.loading = true;
      const { stationId, mobilePhone } = this.currenRowData;
      cardUserList({
        enterpriseId: stationId,
        mobilePhone: mobilePhone,
      }).then((res) => {
        this.loading = false;
        if (res && res.code === 200) {
          this.cardUseRangeFlag = res.data.cardUseRangeFlag;
          if (this.cardUseRangeFlag === "1") {
            this.balanceList = res.data.cardList;
          } else if (this.cardUseRangeFlag === "2") {
            this.balanceList = res.data.cardTypeList;
          }
        } else {
          this.balanceList = [];
        }
      });
    },

    formatterDzkType(row) {
      const types = {
        1: "汽油",
        2: "柴油",
        3: "LNG卡",
        4: "CNG卡",
        0: "通用卡",
      };
      return types[row.cardOilsType];
    },

    balanceDetails(row) {
      console.log(row, "余额");
      console.log(row.cardList);
      this.balanceDetailsList = row.cardList;
      this.isDetails = true;
    },

    // 调整余额按钮
    handleAdjust(row) {
      this.currentCardBlanceTotal = row.totalAmt;
      this.customerCardChangeDto = {
        messagePush: "0",
        amt: null,
        couponId: null,
        operateType: "0",
        stationId: null,
      };
      this.customerCardChangeDto.id = row.id;
      this.showAdjust = true;
      this.$nextTick(() => {
        this.$refs.adjustRef.clearValidate();
      });
    },

    // 确认调整余额
    handleAdjustSubmit() {
      this.$refs.adjustRef.validate((valid) => {
        if (valid) {
          this.adjustSubmitLoading = true;
          let customerCardChangeDto = cloneDeep(this.customerCardChangeDto);
          customerCardChangeDto.mobilePhone = this.currenRowData.mobilePhone;
          customerCardChangeDto.amt = customerCardChangeDto.amt.trim();
          electronicCardUpdateUserRecordApi(customerCardChangeDto).then(
            (res) => {
              this.adjustSubmitLoading = false;
              if (res && res.code === 200) {
                this.$message.success(res.msg);
                this.handleClose();
                this.$emit("reloadData");
                // this.$emit("update:showAdjust", false);
                this.showAdjust = false;
              } else {
                this.$message.error(res.msg);
              }
            }
          );
        }
      });
    },

    // 获取油站列表
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val, status: "1" }).then((res) => {
        this.stationList = res;
        console.log(res[0], 3333);
        if (res.length === 1) {
          this.customerCardChangeDto.stationId = res[0].stationId;
          // this.$nextTick(() => {
          //   this.$refs.adjustRef.clearValidate();
          // });
        }
      });
    },
    // 获取优惠券列表
    async getCouPonList() {
      let enterpriseId;
      if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
        enterpriseId = this.presentEnterprise.enterpriseId;
      }
      const res = await creationList({ status: 1, enterpriseId });
      this.couponList = res.rows;
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-form--label-top .el-form-item {
  // .el-form-item__label {
  //   border-left: 6px solid orange;
  //   padding: 0;
  //   padding-left: 10px;
  //   line-height: 30px;
  // }

  // &:nth-of-type(4) {
  //   .el-form-item__label {
  //     border-left: none !important;
  //   }
  // }
}
</style>
